/*************************************************************************
 * File Name:    Swap_Nodes_in_Pairs.cc
 * Author:       zero91
 * Mail:         jianzhang9102@gmail.com
 * Created Time: 2013/11/13 23:02:38
 * 
 * Description:  
 |------------------------------------------------------------------------
 | Problem: Swap Nodes in Pairs
 |
 | Given a linked list, swap every two adjacent nodes and return its head.
 |
 | For example,
 | Given 1->2->3->4, you should return the list as 2->1->4->3.
 |
 | Your algorithm should use only constant space. You may not modify the values
 | in the list, only nodes itself can be changed.
 |------------------------------------------------------------------------
 ************************************************************************/

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>

using namespace std;

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
	ListNode *swapPairs(ListNode *head)
	{
		if (head == NULL || head->next == NULL) return head;
		ListNode *t, *ans;

        ans = head->next;
		head->next = ans->next;
		ans->next = head;

		for (ListNode *tail = head; tail->next != NULL; tail = tail->next->next) {
			if (tail->next->next == NULL) break;
			t = tail->next;
			tail->next = t->next;
			t->next = tail->next->next;
			tail->next->next = t;
        }
		return ans;
    }
};

